package com.dingwei.lesyndrome.ui.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.dingwei.lesyndrome.R;
import com.dingwei.lesyndrome.app.MyApplication;
import com.dingwei.lesyndrome.bean.PeripheralDetailBean;
import com.dingwei.lesyndrome.bean.SelectedMerchantsBean;
import com.dingwei.lesyndrome.mvp.presenter.PeripheralDetailPresenter;
import com.dingwei.lesyndrome.mvp.view.Contract;
import com.jaeger.library.StatusBarUtil;
import com.lihao.baselibrary.base.BaseActivity;
import com.lihao.baselibrary.utils.IntentUtils;
import com.lihao.baselibrary.utils.L;
import com.lihao.baselibrary.utils.RegexUtils;
import com.lihao.baselibrary.utils.ScreenUtils;
import com.lihao.baselibrary.weight.TitleBar;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;
import com.zhouwei.mzbanner.holder.MZViewHolder;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created time 2018/3/7.
 * Creator 南柯一梦丶 on
 * Personal signature 余生还长 何必慌张
 * Page description :
 */

public class PeripheralDetailActivity extends BaseActivity implements Contract.PeripheralDetailView {
    PeripheralDetailPresenter peripheralDetailPresenter = new PeripheralDetailPresenter(this);
    @Bind(R.id.banner)
    MZBannerView banner;
    @Bind(R.id.img_back)
    ImageView imgBack;
    @Bind(R.id.img_collect)
    ImageView imgCollect;
    @Bind(R.id.rl_title)
    RelativeLayout rlTitle;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.tv_price)
    TextView tvPrice;
    @Bind(R.id.img_navigation)
    ImageView imgNavigation;
    @Bind(R.id.img_phone)
    ImageView imgPhone;
    @Bind(R.id.webView)
    WebView webView;
    @Bind(R.id.scrollView)
    ScrollView scrollView;
    @Bind(R.id.title_bar)
    TitleBar titleBar;
    @Bind(R.id.ll_title)
    LinearLayout llTitle;
    @Bind(R.id.data_layout)
    RelativeLayout dataLayout;
    @Bind(R.id.no_net_btn)
    TextView noNetBtn;
    @Bind(R.id.no_net_layout)
    RelativeLayout noNetLayout;
    @Bind(R.id.tv_page)
    TextView tvPage;

    private String id;
    private PeripheralDetailBean bean;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_peripheral_detail;
    }

    @Override
    protected void initData() {
        peripheralDetailPresenter.initData(id);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void initView() {
        id = getIntent().getStringExtra("id");

        StatusBarUtil.setTranslucentForImageView(this, 30, null);

        RelativeLayout.LayoutParams lp =new RelativeLayout.LayoutParams(ScreenUtils.getScreenWidth(BaseActivity.context),ScreenUtils.getScreenWidth(BaseActivity.context)/4*3);
        banner.setLayoutParams(lp);

        scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (rlTitle != null && rlTitle.getHeight() > 0) {
                    int height = rlTitle.getHeight();
                    if (scrollY < height) {
                        int alpha = (int) (new Float(scrollY) / new Float(height) * 200);
                        Log.e("yy", "" + alpha);
                        llTitle.setAlpha(alpha/255);
                        if (alpha < 150) {

                        } else {
                            L.e("222222222222");


                        }
                    } else {
                        llTitle.setAlpha(1);
                    }
                }
            }
        });

        banner.addPageChangeLisnter(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tvPage.setText(position+1+"/"+bean.data.imgList.size());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        titleBar.setOnMenuListener(new TitleBar.OnMenuListener() {
            @Override
            public void onMenuClick() {
                peripheralDetailPresenter.collect(id);
            }
        });
    }

    @Override
    public void onFail() {
        showData("fail");
    }

    @Override
    public void setData(PeripheralDetailBean bean) {
        this.bean = bean;
        tvPage.setText(1+"/"+bean.data.imgList.size());
        tvName.setText(bean.data.title);
        tvPrice.setText("￥"+bean.data.price);
        if (bean.data.isCollect) {
            imgCollect.setImageResource(R.drawable.pic53_2);
            titleBar.setMenuImageResource(R.drawable.pic23);
        } else {
            imgCollect.setImageResource(R.drawable.pic53);
            titleBar.setMenuImageResource(R.drawable.pic65);
        }
        if (bean.data.imgList != null && bean.data.imgList.size() > 0) {
            banner.setIndicatorVisible(false);
            // 设置数据
            banner.setPages(bean.data.imgList, new MZHolderCreator<BannerViewHolder>() {
                @Override
                public BannerViewHolder createViewHolder() {
                    return new BannerViewHolder();
                }
            });
            banner.start();
        }

        webView.loadUrl(bean.data.weburl);

        showData("success");

    }

    @Override
    public void collectSuccess() {
        bean.data.isCollect = !bean.data.isCollect;
        if (bean.data.isCollect) {
            imgCollect.setImageResource(R.drawable.pic53_2);
            titleBar.setMenuImageResource(R.drawable.pic23);
        } else {
            imgCollect.setImageResource(R.drawable.pic53);
            titleBar.setMenuImageResource(R.drawable.pic65);
        }
    }

    public void showData(String state) {
        if (state.equals("success")) {
            dataLayout.setVisibility(View.VISIBLE);
            noNetLayout.setVisibility(View.GONE);
        } else {
            dataLayout.setVisibility(View.GONE);
            noNetLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.img_back, R.id.img_collect, R.id.img_navigation, R.id.img_phone, R.id.no_net_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.img_collect:
                peripheralDetailPresenter.collect(id);
                break;
            case R.id.img_navigation:
                showDaoHang();
                break;
            case R.id.img_phone:
                intent = IntentUtils.getDialIntent(bean.data.telephone);
                startActivity(intent);
                break;
            case R.id.no_net_btn:
                peripheralDetailPresenter.initData(id);
                break;
        }
    }

    public static class BannerViewHolder implements MZViewHolder<PeripheralDetailBean.DataBean.ImgListBean> {
        private ImageView mImageView;
        private TextView tvTitle;

        @Override
        public View createView(Context context) {
            // 返回页面布局
            View view = LayoutInflater.from(context).inflate(R.layout.item_news_banner, null);
            mImageView = (ImageView) view.findViewById(R.id.img);
            tvTitle = (TextView) view.findViewById(R.id.tv_title);
            tvTitle.setVisibility(View.GONE);
            return view;
        }

        @Override
        public void onBind(Context context, int position, PeripheralDetailBean.DataBean.ImgListBean data) {
            // 数据绑定
            Glide.with(BaseActivity.context)
                    .load(data.img)
                    .apply(MyApplication.options_no_transform)
                    .into(mImageView);
        }
    }

    public static Dialog dlg;

    public void showDaoHang() {
        dlg = new Dialog(context, R.style.Theme_Light_Dialog);
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_daohang, null);
        view.measure(0, 0);
        TextView tv_baidu = (TextView) view.findViewById(R.id.tv_baidu);
        TextView tv_gaode = (TextView) view.findViewById(R.id.tv_gaode);
        TextView tv_cancel = (TextView) view.findViewById(R.id.tv_cancel);
        tv_baidu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dlg.dismiss();
                if (TextUtils.isEmpty(bean.data.latitude) || TextUtils.isEmpty(bean.data.longitude)) {
                    showToast("终点地址不正确");
                    return;
                }
                if (isAvilible(context, "com.baidu.BaiduMap")) {//传入指定应用包名
                    try {
                        intent = Intent.getIntent("intent://map/direction?" +
                                "destination=latlng:" + bean.data.latitude + "," + bean.data.longitude + "|name:我的目的地" +        //终点
                                "&mode=driving&" +          //导航路线方式
                                "region=" + bean.data.address +           //
                                "&src=联创车盟#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                        context.startActivity(intent); //启动调用
                    } catch (URISyntaxException e) {
                        Log.e("intent", e.getMessage());
                    }
                } else {//未安装
                    //market为路径，id为包名
                    //显示手机上所有的market商店
                    Toast.makeText(context, "您尚未安装百度地图", Toast.LENGTH_LONG).show();
                    Uri uri = Uri.parse("market://details?id=com.baidu.BaiduMap");
                    intent = new Intent(Intent.ACTION_VIEW, uri);
                    context.startActivity(intent);
                }
            }
        });
        tv_gaode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dlg.dismiss();
                if (TextUtils.isEmpty(bean.data.latitude) || TextUtils.isEmpty(bean.data.longitude)) {
                    showToast("终点地址不正确");
                    return;
                }
                if (isAvilible(context, "com.autonavi.minimap")) {
                    try {
                        intent = Intent.getIntent("androidamap://navi?sourceApplication=玩两天&" +
                                "poiname=我的目的地&" +
                                "lat=" + bean.data.latitude + "&lon=" + bean.data.longitude + "&dev=1");
                        context.startActivity(intent);
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(context, "您尚未安装高德地图", Toast.LENGTH_LONG).show();
                    Uri uri = Uri.parse("market://details?id=com.autonavi.minimap");
                    intent = new Intent(Intent.ACTION_VIEW, uri);
                    context.startActivity(intent);
                }
            }
        });
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dlg.dismiss();
            }
        });

        dlg.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dlg.setContentView(view);
        Window dialogWindow = dlg.getWindow();
        //设置dialog在屏幕底部
        dialogWindow.setGravity(Gravity.BOTTOM);
        //设置dialog弹出时的动画效果，从屏幕底部向上弹出
        dialogWindow.setWindowAnimations(R.style.dialogstyle);
        dialogWindow.getDecorView().setPadding(0, 0, 0, 0);
        //获得window窗口的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        //设置窗口宽度为充满全屏
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        //设置窗口高度为包裹内容
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //将设置好的属性set回去
        dialogWindow.setAttributes(lp);
        dlg.show();
    }

    /*
    * 检查手机上是否安装了指定的软件
    * @param context
    * @param packageName：应用包名
    * @return
            */
    public static boolean isAvilible(Context context, String packageName) {
        //获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        //用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<>();
        //从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }

}
